<template>
	<view class="container">
		<view class="bg-white p-30 d-flex align-items-center justify-content-between mb-20">
			<view>
				<text class="mr-20">联系电话</text>
				<text>{{addresses[0].phone}}</text>
			</view>
			<button type="primary" plain class="font-size-sm line-height-1">自动填写</button>
		</view>
		<view class="bg-white p-30 mb-20">
			<view class="font-size-medium font-weight-bold mb-30">取餐时间</view>
			<view class="text-color-primary">冰淇淋/鲜食等产品无需等待，可立即向店员领取</view>
		</view>
		<view class="bg-white pt-30 mb-20">
			<view class="font-size-medium font-weight-bold mb-30 pl-30">商品列表</view>
			<list-cell arrow line-right>
				<view class="w-100 d-flex align-items-center overflow-hidden">
					<scroll-view class="flex-fill overflow-hidden" scroll-x>
						<view class="w-100 d-flex align-items-center">
							<image :src="item.image" class="pro-img" v-for="(item, index) in cart" :key="index"></image>
						</view>
					</scroll-view>
					<view class="flex-shrink-0 ml-20">共{{ cartNum }}件</view>
				</view>
			</list-cell>
			<list-cell arrow last>
				<view class="w-100 d-flex align-items-center justify-content-between">
					<view class="d-flex align-items-center">
						<view>HT券</view>
						<view class="coupon-label">劵</view>
					</view>
					<view class="text-color-assist" @tap="gotocoupon">{{ selectedCouponTitle }}</view>

				</view>
			</list-cell>
			<list-cell arrow last>
				<view class="w-100 d-flex align-items-center justify-content-between overflow-hidden">
					<view class="flex-shrink-0">备注</view>
					<navigator hover-class="none" class="flex-fill ml-40 text-truncate text-right" open-type="navigate"
						url="/pages/pay/remark">{{ remark }}</navigator>
				</view>
			</list-cell>
			<list-cell last>
				<view class="w-100 d-flex justify-content-end align-items-center">
					<text class="font-size-sm">共{{ cartNum }}件商品，小计</text>
					<text
						class="font-size-lg font-weight-bold">￥{{ isCouponUsed ? (cartAmount - selectedCouponMoney) : cartAmount }}</text>
				</view>
			</list-cell>
		</view>
		<list-cell last>
			<view class="w-100 d-flex align-items-center justify-content-between">
				<view>支付方式</view>
				<view class="d-flex align-items-center">
					<image src="https://mp-cc85421a-533b-4b68-b797-f0a3eba335d0.cdn.bspapp.com/order/weixin-pay.png"
						class="wx-pay-icon"></image>
					<view>微信</view>
				</view>
			</view>
		</list-cell>
		<view class="footer">
			<view class="mr-30">
				合计：<text
					class="font-size-lg font-weight-bold">￥{{ isCouponUsed ? (cartAmount - selectedCouponMoney) : cartAmount }}</text>
			</view>
			<button type="primary" @click="gotodingdan">支付</button>
		</view>
		<uni-popup ref="popup" type="bottom">
			<scroll-view scroll-y="true" style="height: 100%;">
				<view style="background-color: #fff;height: 100%;border-radius: 60rpx 60rpx 0 0;width: 100%;">
					<view class="coupon_box">
						<view class="wenyue-font" style="text-align: center;padding-top: 20upx;font-size: 40upx;">
							可用的优惠券</view>
						<view class="coupon-item" v-for="(item, index) in coupon" :key="index"
							@tap="selectCoupon(item)">
							<view class="coupon-money">
								<view class="wenyue-font" style="line-height: 50rpx;font-size: 30rpx;">
									{{item.seller_name}}使用
								</view>
								<view class="layof" style="color:#ff9000">￥{{item.money}}</view>
								<view class="end_time">{{item.end_time}}前使用</view>
								<view>
									<view class="tit">使用类型：<text
											style="font-size: 26rpx;color: black;">{{item.ticket}}</text></view>
									<view class="demand">{{item.title}}</view>
								</view>
								<navigator class="get-btn" style="color:#ff9000;borderColor:#ff9000;background:#ffffff"
									url='/pages/index/index'>立即使用</navigator>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</uni-popup>
	</view>
</template>

<script>
	import coupon from '../../components/coolcoupon2.vue'
	import listCell from '@/components/list-cell/list-cell.vue'
	import {
		mapState
	} from 'vuex'
	import cloudApi from '../../common/cloudApi'
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	export default {
		components: {
			listCell,
			uniPopup,
			coupon
		},
		data() {
			return {
				coupon: [],
				cart: uni.getStorageSync('cart'),
				isCouponUsed: false,
				selectedCouponTitle: '选择可用优惠券',
				finalCartAmount: '',
				selectedCouponMoney: 0,
				selectedCouponId: null // 用于存储用户选择的优惠券的 CouponId
			}
		},
		computed: {
			cartNum() {
				return this.cart.reduce((acc, cur) => acc + cur.number, 0)
			},
			cartAmount() {
				return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
			},
			remark() {
				return this.$store.state.remark
			},
			addresses() {
				// 从 Vuex 中获取地址数据
				return this.$store.state.addresses;
			},
			...mapState(['userInfo'])
		},
		onLoad() {
			this.showCoupon();
		},
		methods: {
			updatecoupon() {
				cloudApi.call({
					name: "updateCoupon",
					data: {
						userId: this.userInfo.userId,
						selectedCouponId: this.selectedCouponId
					},
					success: (res) => {
						console.log(res);
					}
				});
			},
			selectCoupon(selectedCoupon) {
				if (!this.cart || !selectedCoupon) {
					return; // 防御性编程，确保 cart 和 selectedCoupon 存在
				}
				this.selectedCouponId = selectedCoupon.CouponId;
				const selectedProductTypes = this.cart.map(cartItem => cartItem.remark);
				for (const cartItem of this.cart) {
					const selectedProductType = cartItem.remark;

					if (selectedCoupon.remark === 'all' || selectedProductType === selectedCoupon.remark) {
						// 在这里设置要显示的文本和已选择的优惠券金额
						this.selectedCouponTitle = selectedCoupon.title;
						this.selectedCouponMoney = selectedCoupon.money;
						this.isCouponUsed = true;
						this.$refs['popup'].close();
					}
					else{
						uni.showModal({
							title: '提示',
							content: '抱歉,此订单不符合优惠要求'
						});
					}
				}
			},
			showCoupon() {
				this.coupon = this.userInfo.coupon[0].list;
			},
			gotocoupon() {
				this.$refs['popup'].open();
			},
			getCurrentFormattedTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = now.getMonth() + 1; // 月份从 0 开始，所以要加 1
				const day = now.getDate();
				const hours = now.getHours();
				const minutes = now.getMinutes();
				const seconds = now.getSeconds();

				// 格式化日期时间
				const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				return formattedTime;
			},
			removeCouponLocally() {
				// 从本地存储的用户信息中移除优惠券
				const userCouponList = this.userInfo.coupon[0].list;
				const selectedCouponId = this.selectedCouponId;

				for (let i = 0; i < userCouponList.length; i++) {
					if (userCouponList[i].CouponId === selectedCouponId) {
						// 找到匹配的优惠券，将其从列表中移除
						userCouponList.splice(i, 1);
						break; // 假定每个优惠券的 `CouponId` 都是唯一的，找到后即可退出循环
					}
				}
			},
			gotodingdan() {
				const hasItemWithTrademark = this.cart.some(item => item.show_trademark);
				cloudApi.call({
					name: 'createOrder',
					data: {
						userId: this.userInfo.userId,
						status: '进行中',
						cartAmount: this.cartAmount - this.selectedCouponMoney,
						address: this.addresses[0].address,
						productImages: this.cart.map(item => item.image),
						// 其他订单相关参数
						created_at: this.getCurrentFormattedTime() // 添加订单创建时间
					},
					success: (res) => {
						this.updatecoupon();
						this.removeCouponLocally();
						console.log(res)
						if (hasItemWithTrademark) {
							cloudApi.call({
								name: 'updatesign2',
								data: {
									userId: this.userInfo.userId,
								}
							})
						} else {
							// 购物车中没有商品符合条件，可以显示提示或采取其他操作
							console.log('没有商品符合条件');
						}
						uni.switchTab({
							url: '/pages/order/order'
						})
					}
				})
			}
		}
	}
</script>
<style>
	.coupon_box {
		width: 100%;
		height: auto;
		display: table;
		padding: 6upx 26upx 26upx 26upx;
	}

	.other_type {
		width: 100%;
		height: 90upx;
		padding-top: 50upx;
	}

	.text {
		width: 100%;
		border-top: 1px solid #eeeeee;
		display: block;
		text-align: center;
		position: relative;
	}

	.textspan {
		width: 180upx;
		height: 40upx;
		line-height: 40upx;
		color: #999999;
		display: block;
		background: #ffffff;
		position: absolute;
		left: 50%;
		top: 50%;
		margin-left: -90upx;
		margin-top: -20upx;
	}

	.coupon-item {
		width: 100%;
		height: auto;
		display: table;
		border-radius: 30upx;
		padding: 0 20upx;
		margin-top: 22upx;
		border: 1px solid #eeeeee;
		background: linear-gradient(to right, #ffe298, #ffdcfc);
		position: relative;
	}

	.coupon-money {
		width: 465upx;
		height: auto;
		display: table;
		float: left;
		padding: 15upx 0 26upx 0;
		border-width: 10px;
		border-style: none dotted none none;
		border-color: #eeeeee;
	}

	.nick {
		width: 100%;
		height: 50upx;
		line-height: 30upx;
		/* font-size: $font-sm;
				color: $font-color-999; */
	}

	.tit {
		width: 100%;
		height: 50upx;
		line-height: 50upx;
		font-size: 30rpx;
		color: #ff8269;
		font-weight: 550;
	}

	.demand {
		width: 100%;
		height: 30upx;
		line-height: 30upx;
		/* font-size: $font-sm;
				color: $font-color-999; */
	}

	.layof {
		width: 100%;
		height: 48upx;
		line-height: 30upx;
		font-size: 50upx;
		color: #ff8269;
		font-weight: bold;
		padding: 10upx 0;
		margin-bottom: 10upx;
	}

	.end_time {
		width: 100%;
		height: 30upx;
		line-height: 30upx;
		/* font-size: $font-sm;
				color: $font-color-999; */
	}

	.get-btn {
		width: 146upx;
		height: 52upx;
		line-height: 50upx;
		position: absolute;
		top: 50%;
		right: 26upx;
		margin-top: -26upx;
		text-align: center;
		border-radius: 60upx;
		color: #ff9000;
		border: 1px solid #ff9000;
		/* font-size: $font-sm; */
		float: right;
	}

	.coupon-item:after {
		width: 40upx;
		height: 20upx;
		position: absolute;
		left: 460upx;
		top: -1px;
		border-radius: 0 0 40upx 40upx;
		content: "";
		display: block;
		background: #f8f8f8;
		border: 1px solid #eeeeee;
		border-top: 0px;
	}

	.coupon-item:before {
		width: 40upx;
		height: 20upx;
		position: absolute;
		left: 460upx;
		bottom: -1px;
		border-radius: 40upx 40upx 0 0;
		content: "";
		display: block;
		background: #f8f8f8;
		border: 1px solid #eeeeee;
		border-bottom: 0px;
	}
</style>
<style lang="scss" scoped>
	.container {
		height: auto;
		padding-bottom: 120rpx;
	}

	.pro-img {
		width: 120rpx;
		height: 90rpx;
		flex-shrink: 0;
	}

	.coupon-label {
		background-color: $color-primary;
		color: #FFFFFF;
		font-size: 18rpx;
		line-height: 0.9rem;
		width: 0.9rem;
		height: 0.9rem;
		margin-left: 10rpx;
		text-align: center;
		border-radius: 15rpx;
	}

	.wx-pay-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	.footer {
		background-color: #FFFFFF;
		z-index: 10;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;

		button {
			width: 250rpx;
			text-align: center;
			padding: 0;
			height: 100%;
			line-height: 100rpx;
			border-radius: 0 !important;
			font-size: $font-size-lg;
		}
	}
</style>